import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';

function BirdCard() {
  const [birds, setBirds] = useState([]); // 存储鸟类数据
  const [loading, setLoading] = useState(true); // 加载状态
  const [error, setError] = useState(null); // 错误信息
  const navigate = useNavigate(); // 路由导航

  // 组件加载时获取数据
//   useEffect(() => {
//     const fetchBirds = async () => {
//       try {
//         const response = await fetch('http://localhost:5000/birds/getAllBirds');
//         if (!response.ok) {
//           throw new Error('获取数据失败');
//         }
//         const data = await response.json();
//         setBirds(data);
//       } catch (err) {
//         setError(err.message);
//       } finally {
//         setLoading(false);
//       }
//     };

//     fetchBirds();
//   }, []);
useEffect(() => {
    const fetchBirds = async () => {
      try {
        const response = await fetch('http://localhost:5000/birds/getAllBirds');
        if (!response.ok) {
          throw new Error('获取数据失败');
        }
        const data = await response.json();
        console.log('Fetched data:', data); // 添加日志记录

        if (data && typeof data === 'object' && Array.isArray(data.data)) { // 检查数据是否为数组
          setBirds(data.data[0]);
        }else {
            throw new Error('数据格式不正确');
        }
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchBirds();
  }, []);
  // 处理查看详情按钮点击
  const handleDetailsClick = (birdId) => {
    navigate(`/bird/${birdId}`); // 跳转到详情页
  };

  if (loading) return <div>加载中...</div>;
  if (error) return <div>错误: {error}</div>;

  
  console.log('Rendered birds:', birds); // 确认 birds 数据

  return (
    <Container className="mt-4">
      <h2 className="mb-4">鸟类图鉴</h2>
      <Row>
        {birds.map((bird) => (
          <Col key={bird.id} sm={12} md={6} lg={4} className="mb-4">
            <Card style={{ width: '18rem' }}>
              {/* 鸟类图片，如果没有则显示占位图 */}
              <Card.Img 
                variant="top" 
                // src={bird.photo || 'https://via.placeholder.com/180'} 
                src={bird.photo} 
                alt={bird.name}
              />
              <Card.Body>
                <Card.Title>{bird.name}</Card.Title>
                <Card.Text>
                  {bird.description}
                </Card.Text>
                <Button 
                  variant="primary" 
                  onClick={() => handleDetailsClick(bird.id)}
                >
                  查看详情
                </Button>
              </Card.Body>
            </Card>
          </Col>
        ))}
      </Row>
    </Container>
  );
}

export default BirdCard;